package com.rj.framework.component.interceptor.impl;

import com.rj.framework.component.BusinessComponent;
import com.rj.framework.component.interceptor.ComponentInterceptor;
import com.rj.framework.context.Context;
import com.rj.framework.validation.ContextAwareConstraintValidatorFactory;
import jakarta.validation.*;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * 重试拦截器
 *
 * @author YFX_RANLUBO
 * @date 2025/06/27 13:57
 **/
public class ValidationInterceptor implements ComponentInterceptor {

    private ValidatorFactory validatorFactory;

    public Validator getValidator(Context context) {
        if (validatorFactory == null) {
            // 配置验证器工厂（集成上下文）
            validatorFactory = Validation.byDefaultProvider()
                    .configure()
                    .constraintValidatorFactory(new ContextAwareConstraintValidatorFactory(
                            context
                    ))
                    .buildValidatorFactory();
        }

        return validatorFactory.getValidator();
    }


    @Override
    public <I, O, C extends Context<?>> BusinessComponent<I, O, C> intercept(BusinessComponent<I, O, C> component, String componentName) {
        return (input, context) -> {
            Set<ConstraintViolation<I>> violations = getValidator(context).validate(input);
            if (violations.isEmpty()) {
                return component.execute(input, context);
            }
            String violationErr = violations.stream().map(e -> e.getMessage()).collect(Collectors.joining());
            throw new ValidationException(String.format("%s: 输入：%s,校验错误：", componentName, input, violationErr));
        };
    }
}
